#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_i2c.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_errno.h"
#include "aht20.h"
#include "wifiiot_adc.h"

#define AHT20_BAUDRATE 400*1000
#define AHT20_I2C_IDX WIFI_IOT_I2C_IDX_0

#define GAS_SENSOR_CHAN_NAME WIFI_IOT_ADC_CHANNEL_5

float humidity = 0.0f;
float temperature = 0.0f;
unsigned short gas = 0;
unsigned short stat = 0;

void init(void){
    GpioInit();
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_13,WIFI_IOT_IO_FUNC_GPIO_13_I2C0_SDA);
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_14,WIFI_IOT_IO_FUNC_GPIO_14_I2C0_SCL);
    I2cInit(AHT20_I2C_IDX,AHT20_BAUDRATE);
}

static void envionment_task_run(void *arg){
    (void)arg;
    init();
    uint32_t retval = 0;
    while (WIFI_IOT_SUCCESS!=AHT20_Calibrate())
    {
        printf("AHT20 sensor init failed\r\n");
        usleep(1000);
    }
    while (1)
    {
        retval = AHT20_StartMeasure();
        if (retval != WIFI_IOT_SUCCESS)
        {
            printf("trigger measure failed\r\n");
        }else
        {
            retval = AHT20_GetMeasureResult(&temperature,&humidity);
        }
        AdcRead(GAS_SENSOR_CHAN_NAME,&gas,WIFI_IOT_ADC_EQU_MODEL_4,WIFI_IOT_ADC_CUR_BAIS_DEFAULT,0);
        if (temperature < -35 || temperature>25 || humidity > 80 || gas > 1840)
        {
            stat = 2;
        }else if (temperature<10 || temperature>23 ||humidity>70 ||gas>1760)
        {
            stat = 1;
        }else
        {
            stat = 0;
        }
        printf("temp:%4.1f degree,hum:%4.1f %%, gas:%d PPM,stat:%d \r\n",temperature,humidity,gas,stat);
        
        sleep(1);
        
    }
    
}


void envionment_task(void){
    osThreadAttr_t attr;
    attr.name = "envionment_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew(envionment_task_run,NULL,&attr)==NULL)
    {
        printf("environment failed\n");
    }
    
}